using Furion.DatabaseAccessor;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace Pear.Core
{
    /// <summary>
    /// 部门
    /// </summary>
    public class Department : Entity, IEntityTypeBuilder<Department>
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public Department()
        {
            CreatedTime = DateTimeOffset.Now;
            IsDeleted = false;
            Sequence = 0;
            Enabled = true;
        }

        /// <summary>
        /// 部门名称
        /// </summary>
        [Required, MaxLength(32)]
        public string Name { get; set; }
        /// <summary>
        /// 部门图标
        /// </summary>
        public string Icon { get; set; }

        /// <summary>
        /// 电话
        /// </summary>
        public string Telephone { get; set; }
        /// <summary>
        /// 传真
        /// </summary>
        public string Fax { get; set; }
        /// <summary>
        /// 邮箱
        /// </summary>
        public string Email { get; set; }
        /// <summary>
        /// 描述
        /// </summary>
        [MaxLength(200)]
        public string Remark { get; set; }
        /// <summary>
        /// 序号/排序
        /// </summary>
        [Required]
        public int Sequence { get; set; }
        /// <summary>
        /// 是否启用
        /// </summary>
        public bool Enabled { get; set; }
        /// <summary>
        /// 所属部门Id
        /// </summary>
        public int? ParentId { get; set; }
        /// <summary>
        /// 所属部门
        /// </summary>
        public Department Parent { get; set; }
        /// <summary>
        /// 次级列表
        /// </summary>
        public ICollection<Department> Sublevels { get; set; }


        /// <summary>
        /// 部门下所有用户
        /// </summary>
        public ICollection<User> Users { get; set; }


        /// <summary>
        /// 配置实体
        /// </summary>
        /// <param name="entityBuilder"></param>
        /// <param name="dbContext"></param>
        /// <param name="dbContextLocator"></param>
        public void Configure(EntityTypeBuilder<Department> entityBuilder, DbContext dbContext, Type dbContextLocator)
        {
            entityBuilder
                .HasMany(x => x.Sublevels)
                .WithOne(x => x.Parent)
                .HasForeignKey(x => x.ParentId);

            entityBuilder.HasMany(x => x.Users)
            .WithOne(x => x.Department)
            .HasForeignKey(x => x.DepartmentId);
        }

    }
}